package com.atguigu.lease.common.config;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@EnableCaching //启用spring缓存管理
@Configuration
public class RedisConfig implements InitializingBean {
    //我们手动保存缓存时 会装配这个对象使用， springcache不会使用！！
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        //为redisTemplate设置键和值的序列化器

        //redis键 一般使用字符串类型的序列化器
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        //redis值 一般转json字符串处理
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

    }

//    @PostConstruct
//    public void init(){
//
//    }
    // 初始化缓存管理器 注入到ioc容器中
    @Bean //redisConnectionFactory 表示redis连接工厂
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //redis缓存管理器的配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
//                        .disableCachingNullValues() 不缓存空值
                    .entryTtl(Duration.ofMinutes(60)) //缓存的过期时间
                //设置键序列化器
                        .serializeKeysWith(RedisSerializationContext.
                                SerializationPair.fromSerializer(new StringRedisSerializer()))
                //设置值序列化器
                        .serializeValuesWith(RedisSerializationContext.SerializationPair
                                .fromSerializer(new GenericJackson2JsonRedisSerializer()));

        return RedisCacheManager
                //创建构建器：传入连接工厂
                .builder(redisConnectionFactory)
                // redis缓存管理器 的配置信息
                .cacheDefaults(config)
                .build();
    }




}
